<template>
  <div class="table-container">
    <a-card class="mb-3" :bordered="false">
      <div class="flex justify-between">
        <div class="flex">
          <a-button type="primary" @click="addNew">
            {{ t["新增"] }}
          </a-button>
          <a-button @click="search">
            {{ t["刷新"] }}
          </a-button>
        </div>
        <div class="flex">
          <div class="flex gap-2">
            <a-input-search
              v-model="query.fieldName"
              search-button
              :placeholder="t['请输入字段名']"
              :button-text="t['搜索']"
              @search="search"
              allow-clear
              @keydown.enter="search"
            ></a-input-search>
          </div>
          <a-divider :direction="'vertical'" class="h-full"></a-divider>
          <XDelete :disabled="selectedKeys.length <= 0" @ok="delByIds" />
        </div>
      </div>
    </a-card>
    <a-card :bordered="false">
      <a-table
        v-bind="comTableConfig"
        v-model:selectedKeys="selectedKeys"
        :loading="loading"
        :bordered="false"
        size="medium"
        :columns="translateColumns(columns)"
        :data="tableData"
        table-layout-fixed
        :row-selection="rowSelection"
        page-position="bottom"
        row-key="fieldId"
        :pagination="{
          pageSize: query.pageSize,
          total: query.total,
          current: query.pageNum,
          showJumper: true,
          showPageSize: true,
          showTotal: true
        }"
        @page-change="pageChange"
        @page-size-change="pageSizeChange"
      >
        <template #fieldName="{ record }">
          <!-- <span v-if="record.isDel === 'N'">
          {{ tm[record.fieldName] }}
        </span> -->
          <span>
            {{ record.fieldName }}
          </span>
        </template>
        <template #status="{ record }">
          <IconCheck v-if="record.status === '0'" style="color: green"></IconCheck>
          <IconClose v-else style="color: red"></IconClose>
        </template>
        <template #optional="{ record }">
          <a-link :disabled="record.isDel === 'N'" @click="editItem(record)">
            {{ t["编辑"] }}
          </a-link>
          <XDelete :disabled="record.isDel === 'N'" @ok="delByIds(record.fieldId)">
            {{ t["删除"] }}
          </XDelete>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="form.modal"
      :draggable="true"
      :title="t['操作']"
      :footer="false"
      :mask-closable="false"
    >
      <a-form
        :model="form"
        :wrapper-col-props="{ span: 16 }"
        :label-col-props="{ span: 8 }"
        layout="vertical"
        size="large"
        @submit-success="submit"
      >
        <a-form-item
          field="fieldName"
          :rules="{ required: true, message: t['校验失败'] }"
          :label="t['字段名']"
        >
          <a-input v-model="form.fieldName" allow-clear :max-length="100" show-word-limit />
        </a-form-item>

        <a-form-item
          field="fieldType"
          :rules="{ required: true, message: t['校验失败'] }"
          :label="t['类型']"
        >
          <a-radio-group v-model="form.fieldType" :options="filedOptions"> </a-radio-group>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            {{ t["保存"] }}
          </a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { addField, delField, listField, updateField } from "@/api/service/field/field";
import { Field } from "@/api/service/field/type";
import useTableConfig from "@/hook/useTableConfig";

import { IQuery } from "@/interface/IAxios";
import { columns } from "../columns";
import { form, resetForm } from "../form";

const t = translate("公共模块");

const selectedKeys = ref([]);
const loading = ref(true);
const { rowSelection, comTableConfig } = useTableConfig(columns);
const tableData = ref([] as Array<Field>);

const queryConfig: IQuery = {
  orderByColumn: "field_id",
  pageNum: 1,
  pageSize: 20,
  total: 0,
  isAsc: "desc",
  status: "",
  fieldName: ""
};
const query = ref({
  ...queryConfig
});

function getList() {
  loading.value = true;
  listField(query.value).then((res) => {
    tableData.value = res.rows;
    query.value.total = res.total;
    loading.value = false;
  });
}
onMounted(() => {
  getList();
});
function pageChange(index: number) {
  query.value.pageNum = index;
  getList();
}

async function delByIds(id: string) {
  let ids = [];
  if (id) {
    ids = [id];
  } else {
    ids = selectedKeys.value;
  }
  await delField(ids);
  getList();
  selectedKeys.value = [];
}
const filedOptions = [
  {
    label: t.value?.["文本"],
    value: "0"
  },
  {
    label: t.value?.["数字"],
    value: "1"
  },
  {
    label: t.value?.["图片"],
    value: "2"
  },
  {
    label: t.value?.["条形码"],
    value: "3"
  },
  {
    label: t.value?.["二维码"],
    value: "4"
  },
  {
    label: t.value?.["视频"],
    value: "5"
  }
];
/**
 * 注释: 更改页数
 *
 * */
const pageSizeChange = (size: number) => {
  query.value.pageSize = size;
  getList();
};

const addNew = () => {
  resetForm();
  form.value.status = "0";
  form.value.modal = true;
  getList();
};

/**
 * 注释:保存
 *
 * */
const submit = async (validate: any) => {
  if (!validate.errors) {
    if (!form.value.fieldId) {
      await addField(form.value);
    } else {
      await updateField(form.value);
    }
    form.value.modal = false;
  }
  getList();
};
/**
 * 注释:重置筛选
 *
 * */
const resetQuery = () => {
  query.value = {
    ...queryConfig
  };
  selectedKeys.value = [];
  getList();
};
const search = () => {
  query.value.pageNum = 1;
  getList();
};
/**
 * 注释: 编辑
 *
 * */
const editItem = (item: Field) => {
  form.value = {
    ...item,
    modal: true,
    fieldType: item.fieldType
  };
};
</script>
